<?php

namespace app\admin\controller;

use app\client\api\C_goods;
use app\client\admin\C_plugin;
use app\client\common\C_appStore;

class  AppStore
{

    public $c_goods;
    public $c_plugin;
    public $c_appStore;

    /**
     * @menuName 软件商店
     * 上面的是菜单的名字
     * @moduleName 软件列表
     * 上面的是控制器的名字
     */
    public function __construct()
    {
        $this->c_goods = new C_goods();
        $this->c_plugin = new C_plugin();
        $this->c_appStore = new C_appStore();
    }

    /**
     * @actionName  插件列表
     * @show 1
     */
    public function index()
    {
        $authData=array(
            "appStore_install"=>\Authorize_event::checkAuth('app\admin\controller\AppStore',"install"),
        );
        $installed=request()->param("installed",0);
        $paramsObj = paramsObj();
        $paramsObj->params = array(
            "url" => config("app.url"),
        );
        if($installed){
            $response = $this->c_goods->installedPlugin($paramsObj);
            $listData = array();
            if ($response["success"]) {
                $listData = $response["data"];
            }
        }else{
            $response = $this->c_goods->goodList($paramsObj);
            $listData = array();
            if ($response["success"]) {
                $listData = $response["data"];
            }
        }

        $response = $this->c_goods->pluginCategory();
        $category = array();
        if ($response["success"]) {
            $category = $response["data"];
        }

/*        if (env()->get("APP_debug") == 1) {
            //如果是开发者模式,列表加载本地id为负数插件 本地插件不能为0 因为还有安装插件为0
            foreach ($pluginsList as $k => $v) {
                if ($k > 0) {
                    $tempStr = '{"id":-1,"name":"\u6d4b\u8bd5","goodsNo":"SD20240107151756969974025-1","modelId":0,"sellPrice":"--.--","marketPrice":"25.00","costPrice":"0.00","upTime":0,"downTime":0,"createTime":1704611911,"thumb":"","status":0,"keywords":"","description":"","searchWords":"","visit":0,"favorite":0,"sort":99,"specMap":"","comments":0,"sale":0,"grade":0,"sellerId":0,"isShare":0,"content":"","isVirtual":1,"virtualConfig":"{\"id\":2,\"days\":86400}","unit":"","updateTime":1704612543,"isDel":0,"categoryId":256,"storeNums":0,"weight":"","virtualType":1,"createTimeFormat":"2024-01-07 15:18:31","updateTimeFormat":"2024-01-07 15:29:03","upTimeFormat":"","downTimeFormat":"","statusFormat":"\u4e0a\u67b6","specMapFormat":"","virtualConfigFormat":{"id":2,"days":86400},"isShareFormat":"\u5426","virtualTypeFormat":"\u63d2\u4ef6","pluginData":{"id":2,"name":"\u6d4b\u8bd5","desc":"\u4f7f\u7528\u7684\u8bdd\u8bf7\u8054\u7cfb\u6211\u7684\u5fae\u4fe1","guid":"123","isValid":0},"isVirtualFormat":"\u662f","isDelFormat":"\u5426","categoryIdFormat":"\u8fd0\u884c\u73af\u5883"}';
                    $tempArr = toJsonDecode($tempStr);
                    $tempArr["id"] = $k;
                    $tempArr["pluginData"]["id"] = $k;
                    $tempArr["pluginData"]["name"] = $v["pluginDir"];
                    $tempArr["pluginData"]["guid"] = "本地插件";
                    $tempArr["pluginData"]["desc"] = "仅开发者调试使用";
                    $tempArr["debug"] = 1;
                    array_unshift($listData["data"], $tempArr); //本地插件永远显示在上边,方便调试
                }
            }
        }*/
        $data = array();
        $data["authData"] = $authData;
        $data["listData"] = $listData;
        $data["category"] = $category;
        $data["request"] = request()->param();
        return view("admin/appStore/index", $data);
    }

    /**
     * @actionName  安装
     * @show 2
     */
    public function install()
    {
        $data = array();
        $data["request"] = request()->param();
        return view("admin/appStore/install", $data);
    }

    /**
     * @actionName  执行安装
     * @show 2
     */
    public function run()
    {
        $step = request()->param("step");
        if ($step == "1") {
            return $this->pluginDetail();
        } else if ($step == "2") {
            return $this->install();
        } else {
            return $this->download();
        }
    }

    /**
     * @actionName  下载文件-页面
     * @show 2
     */
    public function download()
    {
        $pluginId = request()->param("pluginId");
        $paramsObj = paramsObj();
        $paramsObj->params = array(
            "id" => $pluginId,
        );
        $result = $this->c_goods->pluginInfo($paramsObj);
        $rowData = array();
        if ($result["success"]) {
            $rowData = $result["data"];
            $rowData['fileSize'] = fileInfo($rowData['downUrl'], "content-length");
            $rowData['fileSizeFormat'] = app("ltcmsFormat")->byte($rowData['fileSize']);
        }
        $data = array();
        $data["rowData"] = $rowData;
        $data["request"] = request()->param();
        return view("admin/appStore/download", $data);
    }

    /**
     * @actionName  插件详情
     * @show 2
     */
    public function pluginDetail()
    {
        $pluginId = request()->param("pluginId");
        $paramsObj = paramsObj();
        $paramsObj->params = array(
            "id" => $pluginId,
            "field" => "id,`name`,downUrl,pluginDir,`desc`",
            "format" => 1,
        );
        $result = $this->c_goods->pluginInfo($paramsObj);
        $rowData = array();
        if ($result["success"]) {
            $rowData = $result["data"];
            $rowData['fileSize'] = fileInfo($rowData['downUrl'], "content-length");
            $rowData['fileSizeFormat'] = app("ltcmsFormat")->byte($rowData['fileSize']);
        }
        $data = array();
        $data["rowData"] = $rowData;
        $data["request"] = request()->param();
        return view("admin/appStore/pluginDetail", $data);
    }

    /**
     * @actionName  系统登录
     * @show 2
     */
    public function ltcmsLogin()
    {
        //获取登录页面地址
        $referer=request()->param("referer","")?request()->param("referer"):(isset($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:config("app.url")); //获取来源url
        $paramsObj=paramsObj();
        $paramsObj->params=array(
            "extraData"=>array(
                "scope"=>"snsapi_userinfo",
                "redirect_uri"=>$referer,
            ),
        );
        $checkResult=app("P_oauth_ltcms_plugin")->getLoginUrl($paramsObj);
        $loginUrl="";
        if($checkResult["error_no"]==0){
            $loginUrl=$checkResult["result"]["loginUrl"];
        }
        $data = array();
        $data["loginUrl"] = $loginUrl;
        $data["request"] = request()->param();
        return view("admin/appStore/ltcms_login", $data);
    }

    /**
     * @actionName  登录回调
     * @show 2
     */
    public function callback()
    {
        $param=request()->param();
        parse_str($param["state"],$stateMap);
        $redirect_uri=isset($stateMap["redirect_uri"])?$stateMap["redirect_uri"]:"";
        $paramsObj=paramsObj();
        $paramsObj->params=array(
            "extraData"=>array(
                "code"=>$param["code"],
            ),
        );
        $checkResult=app("P_oauth_ltcms_plugin")->callback($paramsObj);
        if($checkResult["error_no"]==0){
            $result=$checkResult["result"];
            //写入文件
            $runtime=runtimePath();
            $loginFile=$runtime."login_file";
            $users=array();
            $users["guid"]=$result["userInfo"]["guid"];
            $users["nickname"]=$result["userInfo"]["nickname"];
            $users["token"]=$result["accessToken"]["token"];
            $users["userAvatar"]=$result["userInfo"]["userAvatar"];
            file_put_contents($loginFile,toJsonEncode($users));
            if($redirect_uri){
                header("content-type:text/html;charset=utf-8");
                if(strpos($redirect_uri,"/users/callback") === false){
                    //跳转页面
                    $script=<<<EOV
<script>window.top.location.reload();</script>
EOV;
                    echo $script;
                    exit;
                }else{
                    $url=config("app.url");
                    $script=<<<EOV
    "<script>window.top.location.href='{$url}';</script>"
EOV;
                    echo $script;
                    exit;
                }
            }
        }else{
            echo "登录失败";
            exit;
        }
    }

    /**
     * @actionName  使用激活码
     * @show 2
     */
    public function usedByCardName()
    {
        $data = array();
        $data["host"]=parse_url(config("app.url"), PHP_URL_HOST);
        $data["request"] = request()->param();
        return view("admin/appStore/usedByCardName", $data);
    }

    /**
     * @actionName  使用激活码[执行]
     * @show 2
     */
    public function usedByCardNameDo()
    {
        $result = $this->c_appStore->usedByCardName();
        return jsonResponse($result);
    }

    /**
     * @actionName  下载文件[执行]
     * @show 2
     */
    public function downloadFile()
    {
        $result = $this->c_appStore->downloadFile();
        return jsonResponse($result);
    }

    /**
     * @actionName  安装[执行]
     * @show 2
     */
    public function installExec()
    {
        continueExec();
        $this->c_appStore->install();
    }

    /**
     * @actionName  卸载[执行]
     * @show 2
     */
    public function uninstallExec()
    {
        $result = $this->c_appStore->uninstall();
        return jsonResponse($result);
    }

    /**
     * @actionName  插件设置
     * @show 2
     */
    public function setUpView()
    {
        $result = $this->c_appStore->setUpView();
        return $result;
    }
}